import React, { useState, useEffect } from 'react';
import { Card, Form } from 'react-bootstrap';

const AdvancedSettings = ({ config, setConfig }) => {
  // 组件内部默认配置
  const defaultAdvancedConfig = {
    taskTemplate: 'dayzOffline.chernarusplus',
    serverPath: '',
    rconPassword: '',
    profiles: '',
    serverConfig: 'serverDZ.cfg',
    clientPort: 2304,
    freezeCheck: 0,
    scriptDebug: 0,
    enableDebugMonitor: 0,
    filePatching: 0,
    allowFileWrite: 0,
    netlog: 0,
    cpuCores: -1,
    maxCores: 4,
    reservedCores: 1,
    globalQueueSize: 1024,
    disableNight: 0
  };

  // 组件内部状态，用于表单输入临时存储
  const [localConfig, setLocalConfig] = useState(defaultAdvancedConfig);
  // 任务模板选项状态
  const [missionTemplates, setMissionTemplates] = useState([]);
  const [loadingTemplates, setLoadingTemplates] = useState(false);
  const [templateError, setTemplateError] = useState('');

  // 当外部config变化时，更新内部localConfig
  useEffect(() => {
    const mergedConfig = {
      ...defaultAdvancedConfig,
      ...config
    };
    setLocalConfig(mergedConfig);
  }, [config]);

  // 加载任务模板列表
  useEffect(() => {
    const loadMissionTemplates = async () => {
      setLoadingTemplates(true);
      setTemplateError('');
      try {
        // 直接指向后端服务器的API地址
        const response = await fetch('http://localhost:5000/api/mission-templates');
        if (!response.ok) {
          throw new Error('获取任务模板失败');
        }
        const data = await response.json();
        setMissionTemplates(data.templates || []);
      } catch (error) {
        console.error('加载任务模板失败:', error);
        setTemplateError('无法加载任务模板，请检查服务器路径配置');
        // 如果API调用失败，保持默认选项
        setMissionTemplates([
          { value: 'dayzOffline.chernarusplus', label: 'Chernarus Plus' },
          { value: 'dayzOffline.enoch', label: 'Enoch' },
          { value: 'dayzOffline.sakhal', label: 'Sakhal' }
        ]);
      } finally {
        setLoadingTemplates(false);
      }
    };

    loadMissionTemplates();
  }, []);

  // 处理配置变更，同时更新本地状态和全局配置
  const handleConfigChange = (key, value) => {
    setLocalConfig(prev => ({ ...prev, [key]: value }));
    setConfig(prev => ({ ...prev, [key]: value }));
  };

  return (
    <Card className="h-100 border-3 shadow-medium" style={{backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(15px)', borderColor: '#d32f2f', boxShadow: '0 0 20px rgba(211, 47, 47, 0.5), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 0 10px rgba(211, 47, 47, 0.2)'}}>
      <Card.Body style={{color: '#ffffff', maxHeight: '70vh', overflowY: 'auto'}}>
        <h3 style={{ color: '#ff6b6b', marginBottom: '20px', textAlign: 'center' }}>高级服务器设置</h3>
        
        {/* 基础服务器配置 */}
        <div className="mb-6">
          <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>基础服务器配置</h4>
          
          <div className="row">
            <div className="col-md-6">
              <Form.Group className="mb-3">
                <Form.Label>任务模板</Form.Label>
                <Form.Select 
                  value={localConfig.taskTemplate} 
                  onChange={(e) => handleConfigChange('taskTemplate', e.target.value)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                  disabled={loadingTemplates}
                >
                  {loadingTemplates ? (
                    <option value="">加载中...</option>
                  ) : (
                    missionTemplates.length > 0 ? (
                      missionTemplates.map(template => (
                        <option key={template.value} value={template.value}>
                          {template.label}
                        </option>
                      ))
                    ) : (
                      <option value="">未找到任务模板</option>
                    )
                  )}
                </Form.Select>
                {templateError && (
                  <Form.Text className="text-danger" style={{display: 'block', fontSize: '0.9rem'}}>
                    {templateError}
                  </Form.Text>
                )}
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  从服务器mpmissions目录中读取的任务模板
                </Form.Text>
              </Form.Group>
            </div>
            <div className="col-md-6">
              <Form.Group className="mb-3">
                <Form.Label>服务器路径</Form.Label>
                <Form.Control 
                  type="text" 
                  value={localConfig.serverPath} 
                  onChange={(e) => handleConfigChange('serverPath', e.target.value)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  DayZ服务器根目录路径
                </Form.Text>
              </Form.Group>
            </div>
          </div>
          
          <div className="row">
  
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Label>RCON密码</Form.Label>
                <Form.Control 
                  type="password" 
                  value={localConfig.rconPassword} 
                  onChange={(e) => handleConfigChange('rconPassword', e.target.value)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  远程控制台密码，用于管理服务器
                </Form.Text>
              </Form.Group>
            </div>
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Label>客户端端口</Form.Label>
                <Form.Control 
                  type="number" 
                  min="1024" 
                  max="65535" 
                  value={localConfig.clientPort} 
                  onChange={(e) => handleConfigChange('clientPort', parseInt(e.target.value) || 2304)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  客户端连接端口，通常为服务器端口+2
                </Form.Text>
              </Form.Group>
            </div>
          </div>
        </div>
        
        {/* 文件和路径配置 */}
        <div className="mb-6">
          <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>文件和路径配置</h4>
          
          <div className="row">
            <div className="col-md-6">
              <Form.Group className="mb-3">
                <Form.Label>配置文件目录</Form.Label>
                <Form.Control 
                  type="text" 
                  value={localConfig.profiles} 
                  onChange={(e) => handleConfigChange('profiles', e.target.value)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  服务器配置文件存储目录
                </Form.Text>
              </Form.Group>
            </div>
            <div className="col-md-6">
              <Form.Group className="mb-3">
                <Form.Label>服务器配置文件路径</Form.Label>
                <Form.Control 
                  type="text" 
                  value={localConfig.serverConfig} 
                  onChange={(e) => handleConfigChange('serverConfig', e.target.value)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  服务器主要配置文件，通常为serverDZ.cfg
                </Form.Text>
              </Form.Group>
            </div>
          </div>
          

        </div>
        
        {/* 调试与日志设置 */}
        <div className="mb-6">
          <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>调试与日志设置</h4>
          
          <div className="row">
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check 
                  type="switch" 
                  checked={localConfig.freezeCheck === 1} 
                  onChange={() => handleConfigChange('freezeCheck', localConfig.freezeCheck === 1 ? 0 : 1)} 
                  label="启用冻结检查" 
                  className="form-switch-glow"
                />
              </Form.Group>
            </div>
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check 
                  type="switch" 
                  checked={localConfig.scriptDebug === 1} 
                  onChange={() => handleConfigChange('scriptDebug', localConfig.scriptDebug === 1 ? 0 : 1)} 
                  label="启用脚本调试" 
                  className="form-switch-glow"
                />
              </Form.Group>
            </div>
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check 
                  type="switch" 
                  checked={localConfig.enableDebugMonitor === 1} 
                  onChange={() => handleConfigChange('enableDebugMonitor', localConfig.enableDebugMonitor === 1 ? 0 : 1)} 
                  label="启用调试监视器" 
                  className="form-switch-glow"
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  控制是否在游戏中显示调试信息
                </Form.Text>
              </Form.Group>
            </div>
          </div>
          
          <div className="row">
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check 
                  type="switch" 
                  checked={localConfig.filePatching === 1} 
                  onChange={() => handleConfigChange('filePatching', localConfig.filePatching === 1 ? 0 : 1)} 
                  label="启用文件修补" 
                  className="form-switch-glow"
                />
              </Form.Group>
            </div>
          </div>
          <div className="row">
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check 
                  type="switch" 
                  checked={localConfig.allowFileWrite === 1} 
                  onChange={() => handleConfigChange('allowFileWrite', localConfig.allowFileWrite === 1 ? 0 : 1)} 
                  label="允许文件写入" 
                  className="form-switch-glow"
                />
              </Form.Group>
            </div>
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check 
                  type="switch" 
                  checked={localConfig.netlog === 1} 
                  onChange={() => handleConfigChange('netlog', localConfig.netlog === 1 ? 0 : 1)} 
                  label="启用网络日志" 
                  className="form-switch-glow"
                />
              </Form.Group>
            </div>
          </div>
        </div>
        
        {/* 性能配置 */}
        <div className="mb-6">
          <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>性能配置</h4>
          
          <div className="row">
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Label>CPU核心数</Form.Label>
                <Form.Control 
                  type="number" 
                  min="-1" 
                  value={localConfig.cpuCores} 
                  onChange={(e) => handleConfigChange('cpuCores', parseInt(e.target.value) || -1)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  指定服务器使用的CPU核心数量，设为-1表示系统自动分配
                </Form.Text>
              </Form.Group>
            </div>
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Label>最大核心数</Form.Label>
                <Form.Control 
                  type="number" 
                  min="1" 
                  value={localConfig.maxCores} 
                  onChange={(e) => handleConfigChange('maxCores', parseInt(e.target.value) || 4)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  服务器使用的最大核心数
                </Form.Text>
              </Form.Group>
            </div>
          </div>
          
          <div className="row">
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Label>保留核心数</Form.Label>
                <Form.Control 
                  type="number" 
                  min="0" 
                  value={localConfig.reservedCores} 
                  onChange={(e) => handleConfigChange('reservedCores', parseInt(e.target.value) || 1)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  为系统保留的CPU核心数
                </Form.Text>
              </Form.Group>
            </div>
          </div>
        </div>
        
        {/* 安全与反作弊设置 */}
        <div className="mb-6">
          <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>安全与反作弊设置</h4>
          
          <div className="row">
            <div className="col-md-6">
              <Form.Group className="mb-3">
                <Form.Label>速度黑客检测</Form.Label>
                <Form.Control 
                  type="number" 
                  id="detectedSpeedHack" 
                  min="0" 
                  max="10" 
                  step="0.1" 
                  value={localConfig.detectedSpeedHack} 
                  onChange={(e) => handleConfigChange('detectedSpeedHack', parseFloat(e.target.value) || 0)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  启用速度黑客检测，值范围1-10（1严格，10宽松，可以是浮点数）
                </Form.Text>
              </Form.Group>
            </div>
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check 
                  type="switch" 
                  checked={localConfig.protectMultiHack === 1} 
                  onChange={() => handleConfigChange('protectMultiHack', localConfig.protectMultiHack === 1 ? 0 : 1)} 
                  label="多账户防护" 
                  className="form-switch-glow"
                />
              </Form.Group>
            </div>
  
          </div>
          
          <div className="row">
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check 
                  type="switch" 
                  checked={localConfig.verifyScheduledShots === 1} 
                  onChange={() => handleConfigChange('verifyScheduledShots', localConfig.verifyScheduledShots === 1 ? 0 : 1)} 
                  label="射击验证" 
                  className="form-switch-glow"
                />
              </Form.Group>
            </div>
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check 
                  type="switch" 
                  checked={localConfig.verifyWeaponFire === 1} 
                  onChange={() => handleConfigChange('verifyWeaponFire', localConfig.verifyWeaponFire === 1 ? 0 : 1)} 
                  label="武器射击验证" 
                  className="form-switch-glow"
                />
              </Form.Group>
            </div>
          </div>
        </div>
        
        {/* 队列配置 */}
        <div className="mb-6">
          <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>队列配置</h4>
          
          <div className="row">
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Label>全局队列大小</Form.Label>
                <Form.Control 
                  type="number" 
                  min="1" 
                  value={localConfig.globalQueueSize} 
                  onChange={(e) => handleConfigChange('globalQueueSize', parseInt(e.target.value) || 1024)} 
                  className="glass-input"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  全局队列大小，影响服务器处理能力
                </Form.Text>
              </Form.Group>
            </div>
          </div>
        </div>
        
        {/* 高级时间设置 */}
        <div className="mb-6">
          <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>高级时间设置</h4>
          
          <div className="row">
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Label>日夜循环</Form.Label>
                <Form.Check 
                  type="switch" 
                  checked={localConfig.disableNight === 1} 
                  onChange={() => handleConfigChange('disableNight', localConfig.disableNight === 1 ? 0 : 1)} 
                  label="禁用夜晚" 
                  className="form-switch-glow"
                />
              </Form.Group>
            </div>
          </div>
          <div className="row">
            <div className="col-md-6">
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                注意：夜晚亮度设置已移至基本设置中的游戏体验设置部分
              </Form.Text>
            </div>
          </div>
        </div>
        
        {/* 额外高级设置 */}
        <div className="mb-6">
          <h4 style={{color: '#ff6b6b', marginBottom: '15px', borderBottom: '1px solid rgba(255,255,255,0.1)', paddingBottom: '5px'}}>额外高级设置</h4>
          
          <div className="row">
            <div className="col-md-6">
              <Form.Group className="mb-3">
                <Form.Label>最大同时AI数量</Form.Label>
                <Form.Control
                  type="number"
                  value={localConfig.maxSimultaneousInstances || 100}
                  onChange={(e) => handleConfigChange('maxSimultaneousInstances', parseInt(e.target.value) || 100)}
                  min="10"
                  max="500"
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                  placeholder="设置最大同时AI数量"
                />
              </Form.Group>
            </div>
            <div className="col-md-6">
              <Form.Group className="mb-3">
                <Form.Label>服务器名称后缀</Form.Label>
                <Form.Control
                  type="text"
                  value={localConfig.hostnameSuffix || ''}
                  onChange={(e) => handleConfigChange('hostnameSuffix', e.target.value)}
                  style={{backgroundColor: 'rgba(255,255,255,0.1)', backdropFilter: 'blur(10px)', border: '1px solid rgba(255,255,255,0.2)', color: '#ffffff'}}
                  placeholder="设置服务器名称后缀"
                />
              </Form.Group>
            </div>
          </div>
          
          <div className="row">
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check
                  type="switch"
                  checked={localConfig.preventZoneCleanup || false}
                  onChange={(e) => handleConfigChange('preventZoneCleanup', e.target.checked ? 1 : 0)}
                  label="防止区域清理"
                  className="form-switch-glow"
                />
                <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                  阻止服务器自动清理区域
                </Form.Text>
              </Form.Group>
            </div>
            <div className="col-md-4">
              <Form.Group className="mb-3">
                <Form.Check
                  type="switch"
                  checked={localConfig.disableRadar || false}
                  onChange={(e) => handleConfigChange('disableRadar', e.target.checked ? 1 : 0)}
                  label="禁用雷达"
                  className="form-switch-glow"
                />
              </Form.Group>
            </div>

          </div>
          <div className="row">
            <div className="col-md-6">
              <Form.Text className="text-muted" style={{color: '#ffffff', opacity: 1, display: 'block', fontSize: '0.9rem'}}>
                注意：个人光源设置已移至基本设置中的游戏体验设置部分
              </Form.Text>
            </div>
          </div>
        </div>
      </Card.Body>
    </Card>
  );
};

export default AdvancedSettings;